from sqlalchemy import *
from sqlalchemy.orm import *
from sqlalchemy.ext.declarative import declarative_base

import db
import base64
from config import *
from events import event
from users import user
from eventrsvps import eventrsvp

class eventcontroller(object):
	lookup = None
	def __init__(self, lup ):
		self.lookup = lup

	def index(self, msg=None):
		sess = db.getsession()
		try:
			evts = sess.query(event).all()
		except Exception, e:
			evts = None
			print e
		return self.lookup.get_template("events.html").render(events=evts, msg=msg)
	index.exposed = True

	def editevent(self, eventid=None):
		sess = db.getsession()
		if eventid:
			e = sess.query(event).filter(event.EVENTID == eventid).one()
			rsvps = sess.query(eventrsvp).filter(eventrsvp.EVENTID == eventid).all()
			return self.lookup.get_template("editevent.html").render(e = e, ersvp = rsvps, table=db.event_table)
		else:
			return self.lookup.get_template("editevent.html").render(e = event(), ersvp = None, table=db.event_table)
	editevent.exposed = True

	def deleteevent(self, eventid):
		sess = db.getsession()
		try:
			e = sess.query(event).filter(event.EVENTID == eventid).one()
			sess.delete(e)
			sess.flush()
			return self.index(msg="Successfully Deleted Event")
		except:
			return self.index(msg="Failed to  Delete Event")
	deleteevent.exposed = True

	def listrsvps(self, eventid):
		sess = db.getsession()
		rsvps = sess.query(eventrsvp).filter(eventrsvp.EVENTID == eventid).all()
		return self.lookup.get_template("rsvps.html").render(ersvp = rsvps)
	listrsvps.exposed = True

	def addrsvp(self, eventid):
		sess = db.getsession()
		# this needs to turn into a join
		userids = sess.query(user).all()
		return self.lookup.get_template("addrsvp.html").render(validusers = userids)	
	addrsvp.exposed = True

	def saveevent(self, **kwargs):
		sess = db.getsession()
		try:
			e = sess.query(event).filter(event.EVENTID == kwargs['EVENTID']).one()
		except:
			e = event()
			sess.save(e)

		for k in kwargs:
			if kwargs[k]:
				setattr(e, k, kwargs[k])
				
		print e.TITLE
		e.EVENTDATE = parsedate(e.EVENTDATE)
		try:
			sess.flush()
			msg = "Event "+ e.TITLE+ " has been saved"
		except Exception, e:
			msg = "Failed to Save Event "+str(e)
		return self.index(msg=msg)
	saveevent.exposed = True

	def saversvp(self, userid, eventid):
		sess = db.getsession()
		rsvp = eventrsvp()
		rsvp.USERID = userid
		rsvp.EVENTID = eventid
		try:
			sess.save(rsvp)
			sess.flush()
		except Exception, e:
			print "Error ", e
		return self.listrsvps(eventid = eventid)
	saversvp.exposed = True
		
	def cancelrsvp(self, rsvpid, eventid):
		sess = db.getsession()
		rsvp = sess.query(eventrsvp).filter(eventrsvp.RSVPID == rsvpid).one()
		sess.delete(rsvp)
		sess.flush()
		return self.listrsvps(eventid = eventid)
	cancelrsvp.exposed = True
